<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/4
 * Time: 9:35
 */

namespace app\api\model;


class Recommend extends BaseModel
{
    public static function add($user, $recommender_id = 0)
    {
        $recommender = self::get(['user_id' => $recommender_id]);
        if (!$recommender) {
            $recommender = self::get(['user_id' => 0]);
        }
        $rgt = $recommender['rgt'];
        self::where('rgt', '>=', $rgt)->setInc('rgt', 2);
        self::where('lft', '>=', $rgt)->setInc('lft', 2);
        $data = [
            'user_id' => $user['id'],
            'nickname' => $user['nickname'],
            'lft' => $rgt,
            'rgt' => $rgt + 1,
            'is_promoter' => 0,
        ];
        self::create($data)->save();
    }

    public static function getPromoterID($user_id)
    {
        $user = self::get(['user_id' => $user_id]);
        $promoter = self::where('lft', '<', $user['lft'])->where('rgt', '>', $user['rgt'])->where('is_promoter', '=', 1)->order('lft desc')->find();
        return $promoter['user_id'];
    }

    public static function team($user_id){
        $user = self::get(['user_id' => $user_id]);
        $count = self::where('lft', '>',$user['lft'])->where('rgt','<' ,$user['rgt'])->count('id');
        return $count;
    }
}